package com.wt.struggle.goodbye.main.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.*
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.design.widget.TabLayout
import android.support.v4.app.ActivityCompat
import android.support.v4.app.FragmentManager
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.StaggeredGridLayoutManager
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.TranslateAnimation
import com.google.gson.reflect.TypeToken
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.*
import com.wt.struggle.goodbye.info.FileInfo
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.VideoInfo
import com.wt.struggle.goodbye.main.adapter.PicAdapter
import com.wt.struggle.goodbye.main.fragment.*
import com.wt.struggle.goodbye.sq.adapter.ColorAdapter
import com.wt.struggle.goodbye.sq.adapter.LableAdapter
import com.xin.lv.yang.utils.info.HttpInfo
import com.xin.lv.yang.utils.info.PicItem
import com.xin.lv.yang.utils.utils.DataUtil
import com.xin.lv.yang.utils.utils.FileUtils
import com.xin.lv.yang.utils.utils.StatusBarUtil
import kotlinx.android.synthetic.main.head.*
import kotlinx.android.synthetic.main.send_tie_layout.*
import org.json.JSONObject
import java.io.File
import java.lang.StringBuilder
import java.net.URLDecoder

/**
 * 发起帖子
 */
class SendTieActivity : ProActivity() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            Send.SAVE_TIE_CODE -> {
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort("发表成功")
                    finish()
                }
            }

            Send.ADD_TEXT_CODE -> {
                if (netInfo.code == Config.SUCCESS) {
                    showToastShort("添加成功")
                    getLabTextList()
                }
            }

            Send.GET_TALK_CODE -> {
                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult
                    if (result != null && result != "" && result != "null") {
                        val jsonObject = JSONObject(result)
                        val topicInfoList = jsonObject.optString("topicInfoList")
                        if (topicInfoList != null && topicInfoList != "" && topicInfoList != "null") {
                            val arr: ArrayList<FileInfo> =
                                gson!!.fromJson(topicInfoList, object : TypeToken<ArrayList<FileInfo>>() {}.type)
                            initLabel(arr)
                        }

                    }
                }
            }

            Send.GET_SHE_QU_CODE -> {
                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult
                    if (result != null && result != "" && result != "null") {
                        val arr: ArrayList<FileInfo> =
                            gson!!.fromJson(result, object : TypeToken<ArrayList<FileInfo>>() {}.type)
                        initSheQu(arr)
                    }
                }
            }

            Send.UPLOAD_PIC -> {

                removeLoadDialog()

                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult
                    log("result------$result")

                    if (result != null && result != "" && result != "null") {

                        val jsonObject = JSONObject(result)
                        val id = jsonObject.optString("id")

                        picList.add(id)

                        showPic(id)

                    }
                } else {
                    removeLoadDialog()
                }

            }

            Send.UPLOAD_PIC_MORE -> {

                if (netInfo.code == Config.SUCCESS) {

                    val result = netInfo.dataResult

                    log("result------$result")

                    if (result != null && result != "" && result != "null") {

                        val jsonObject = JSONObject(result)
                        val id = jsonObject.optString("id")

                        picList.add(id)

                        showMoreList(arg1, id)

                        if (chooseMoreIndexNum == choosePicList.size) {
                            removeLoadDialog()
                        } else {
                            chooseMoreIndexNum++
                        }
                    }
                }

            }

            Send.VIDEO_UP -> {

                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult

                    log("result返回------$result")

                    if (result != null && result != "" && result != "null") {
                        val jsonObject = JSONObject(result)
                        val id = jsonObject.optString("id")
                        videoList.add(id)
                        showVideo(id)
                    }
                }
            }

            Send.VOICE_UP -> {

                removeLoadDialog()
                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult

                    log("result返回------$result")

                    showToastShort("音频上传成功")

                    if (result != null && result != "" && result != "null") {
                        val jsonObject = JSONObject(result)
                        val id = jsonObject.optString("id")

                        voiceList.add(id)

                        showVoice(id)

                    }
                }
            }
        }
    }

    /**
     * 显示多图  position 为上传的集合位置     picId 为上传图片的id
     */
    private fun showMoreList(position: Int, picId: String) {
        picAdapter.updateInfo(1, picId, choosePicList[position])
    }

    /**
     * 显示音频
     */
    private fun showVoice(id: String) {

        isVoiceAddPic = true

        picAdapter.updateInfo(3, id, chooseVoice!!)

    }

    /**
     * 显示视频信息
     */
    private fun showVideo(id: String) {

        val path = chooseVideoUri!!.path

        log("视频本地信息-------$path")

        picAdapter.updateInfo(2, id, path)

    }


    /**
     * 显示图片
     */
    private fun showPic(picUrl: String) {

        val top = picRecyclerView.top

        nestScrollView.scrollTo(0, top)

        when (chooseCode) {
            1 -> picAdapter.updateInfo(1, picUrl, chooseFile!!.absolutePath)
            2 -> picAdapter.updateInfo(1, picUrl, picItem!!.uri)
            3 -> picAdapter.updateInfo(1, picUrl, picUrl)
            4 -> {
                Log.i("result", "------" + Config.GET_IMAGE_URL + picUrl)
                picAdapter.updateInfo(4, picUrl, Config.GET_IMAGE_URL + picUrl)
            }

        }

    }

    /**
     * 返回的图片id集合
     */
    val picList: ArrayList<String> = arrayListOf()

    /**
     * 视频集合
     */
    val videoList = arrayListOf<String>()

    /**
     * 音频集合
     */
    val voiceList = arrayListOf<String>()

    /**
     * 显示社区信息
     */
    private fun initSheQu(arr: ArrayList<FileInfo>) {
        this.sheQuList = arr
        for (temp in arr) {
            temp.selector = false
        }

        sheQuRecyclerView.layoutManager =
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
        sheQuAdapter = LableAdapter(this, arr)
        sheQuRecyclerView.adapter = sheQuAdapter
        sheQuAdapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {
                sheQuAdapter.update(position)
            }

            override fun onLongClick(position: Int) {

            }
        }

        sheQuAdd.setOnClickListener {
            addSheQuText()
        }

    }

    /**
     * 添加社区信息
     */
    private fun addSheQuText() {

    }

    var manager: FragmentManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.send_tie_layout)
        tvTitle.text = "发帖"
        tvRight.text = "发布"
        tvRight.setTextColor(resources.getColor(R.color.red))
        manager = supportFragmentManager

        etContent.isFocusable = false

        imageBack.setOnClickListener {

            if (locationManager != null) {
                locationManager!!.removeUpdates(locationListener)
                locationManager = null
                locationListener = null
            }

            finish()

        }

        tvRight.setOnClickListener {
            save()
        }

        imageClose.setOnClickListener {
            fragmentFrameLayout.visibility = View.GONE
            hideInPut(etContent)
        }

        etContent.setOnTouchListener { view, motionEvent ->
            etContent.requestFocus()
            etContent.findFocus()
            etContent.isFocusable = true
            etContent.isFocusableInTouchMode = true

            fragmentFrameLayout.visibility = View.GONE

            false
        }

        setLayoutAnim()

        initLabelColor()

        initRadioGroup()

        getLabTextList()

        getSheQuList()

        initPicRecyclerView()


        if (isLocationEnabled(this)) {
            getLocation()
        } else {
            showLocation()
        }

    }


    /**
     * 显示去打开位置服务
     */
    private fun showLocation() {
        val dialog = AlertDialog.Builder(this)
        dialog.setMessage("是否去设置打开位置服务?")
            .setPositiveButton("确定") { dd, i ->
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                startActivityForResult(intent, 6666)
                dd.dismiss()
            }.setNegativeButton("取消") { _, _ ->

            }.show()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 6666) {
            getLocation()
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK &&
            event!!.action == KeyEvent.ACTION_DOWN
        ) {

            if (locationManager != null) {
                locationManager!!.removeUpdates(locationListener)
                locationManager = null
                locationListener = null
            }
        }

        return super.onKeyDown(keyCode, event)

    }

    private fun setLayoutAnim() {
        fragmentFrameLayout.animation = AnimationUtils.loadAnimation(this, R.anim.enter_pop)
    }


    /**
     * 获取位置服务定位
     */
    private fun getLocation() {
        val code = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val code2 = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

        if (code == PackageManager.PERMISSION_GRANTED && code2 == PackageManager.PERMISSION_GRANTED) {

            get()

        } else {

            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
                5678
            )
        }

    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 5678) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                grantResults[1] == PackageManager.PERMISSION_GRANTED
            ) {

                get()

            }
        }
    }

    var location: Location? = null
    var addressStr: String = ""
    var country = ""

    var locationManager: LocationManager? = null

    @SuppressLint("MissingPermission")
    fun get() {

        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val locationProvider = LocationManager.NETWORK_PROVIDER

        // 获取Location
        location = locationManager!!.getLastKnownLocation(locationProvider)

        // 监视地理位置变化
        locationManager!!.requestLocationUpdates(locationProvider, 5000, 1f, locationListener)


    }


    private var locationListener: LocationListener? = object : LocationListener {

        override fun onLocationChanged(p0: Location?) {
            this@SendTieActivity.location = p0

            val geocoder = Geocoder(this@SendTieActivity)

            val arr = geocoder.getFromLocation(location!!.latitude, location!!.longitude, 1);

            if (arr.size != 0) {

                val address = arr[0]

                Log.i("result", "-------$address")

                country = address.adminArea + address.thoroughfare

                addressStr = address.featureName

                showToastShort("当前位置: $addressStr")
            }

        }

        override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {

        }

        override fun onProviderEnabled(p0: String?) {

        }

        override fun onProviderDisabled(p0: String?) {

        }
    }


    /**
     * 显示图片或者视频的集合信息
     */
    val showPicList = arrayListOf<FileInfo>()


    lateinit var picAdapter: PicAdapter


    private fun initPicRecyclerView() {

        val manager = object : GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }

        picRecyclerView.layoutManager = manager
        picAdapter = PicAdapter(this, showPicList)
        picAdapter.code = 2
        picRecyclerView.adapter = picAdapter

    }

    /**
     * 获取社区列表
     */
    private fun getSheQuList() {
        send!!.getSheQuList(handler)
    }

    /**
     * 获取话题标签
     */
    private fun getLabTextList() {
        send!!.getTalkList(handler!!)
    }

    var indexFragment: ProV4Fragment? = null

    val fragmentArr = arrayListOf<ProV4Fragment>(
        NullFragment(),
        VoiceFragment(),
        ChoosePhotoFragment(),
        ExpressionFragment()
    )


    private fun initRadioGroup() {

        val tt = manager!!.beginTransaction()
        indexFragment = fragmentArr[0]
        tt.add(R.id.fragmentFrameLayout, indexFragment)
        tt.commit()

        sendTieTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabReselected(tab: TabLayout.Tab?) {
                change(tab)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                change(tab)
            }

        })

    }

    private fun change(tab: TabLayout.Tab?) {

        val tttt = manager!!.beginTransaction()

        hideInPut(etContent)

        fragmentFrameLayout.visibility = View.VISIBLE

        when (tab!!.position) {

////            0 -> indexFragment = switchContent(indexFragment!!, fragmentArr[1], R.id.fragmentFrameLayout, tttt)

            0 -> indexFragment = switchContent(indexFragment!!, fragmentArr[2], R.id.fragmentFrameLayout, tttt)

////            1 -> indexFragment = switchContent(indexFragment!!, fragmentArr[3], R.id.fragmentFrameLayout, tttt)

        }
    }


    var isVoiceAddPic = false

    /**
     * 保存
     */
    private fun save() {

        val content = etContent.text.toString()
        val shequInfo = getSheQuInfo()
        val labInfo = getLabText()
        val colorInfo = getColorInfo()

        when {
            content == "" -> showToastShort("请输入内容")
            shequInfo == null -> showToastShort("请选择社区")
            labInfo == null -> showToastShort("请选择标签")

            location == null -> showToastShort("请等待定位完成")

            picList.size == 0 && videoList.size == 0 -> showToastShort("请选择图片或者视频")

            else -> {

                sendSave(content, shequInfo, labInfo, colorInfo, location)

//
//                if (voiceList.size != 0 && picList.size == 0) {
//                    isVoiceAddPic = true
//                    showToastShort("请给音频配图片")
//                } else {
//                    sendSave(content, shequInfo, labInfo, colorInfo, location)
//                }
//

            }
        }
    }


    private fun getSheQuInfo(): FileInfo? {
        if (sheQuList != null && sheQuList!!.size != 0) {
            for (temp in sheQuList!!) {
                if (temp.selector) {
                    return temp
                }
            }
        }

        return null

    }

    /**
     * 保存数据
     */
    private fun sendSave(
        content: String,
        shequInfo: FileInfo?,
        labInfo: FileInfo?,
        colorInfo: FileInfo?,
        location: Location?
    ) {

        val list: ArrayList<HttpInfo> = arrayListOf()
        list.add(HttpInfo("circleId", shequInfo!!.id.toString()))
        list.add(HttpInfo("topicId", labInfo!!.id.toString()))

        val resultContent = DataUtil.getString(content)

        log("--------$resultContent")

        list.add(HttpInfo("content", resultContent))

        list.add(HttpInfo("pics", buildPic(picList)))
        list.add(HttpInfo("audios", buildPic(voiceList)))
        list.add(HttpInfo("videos", buildPic(videoList)))

        if (location != null) {

            list.add(HttpInfo("lat", location.latitude.toString()))
            list.add(HttpInfo("lng", location.longitude.toString()))

            list.add(
                HttpInfo(
                    "location", if (addressStr != "") {
                        if (country != "") {
                            "$country|$addressStr"
                        } else {
                            addressStr
                        }

                    } else {
                        ""
                    }
                )
            )
        }

        list.add(HttpInfo("deviceInfo", ""))
        send!!.sendSaveTie(list, handler)
    }

    private fun buildPic(arr: ArrayList<String>): String {
        val sb = StringBuilder()
        for (i in arr.indices) {
            val temp = arr[i]
            sb.append(temp)
            if (i < arr.size - 1) {
                sb.append(",")
            }

        }
        return sb.toString()

    }

    private fun getColorInfo(): FileInfo? {
        for (temp in colorInfoList) {
            if (temp.selector) {
                return temp
            }
        }
        return null

    }

    private fun getLabText(): FileInfo? {
        for (temp in labTextList!!) {
            if (temp.selector) {
                return temp
            }
        }
        return null

    }

    lateinit var colorAdapter: ColorAdapter
    val colorInfoList = arrayListOf<FileInfo>()

    /**
     * 初始化颜色信息
     */
    private fun initLabelColor() {
        for (temp in colorList) {
            val info = FileInfo()
            info.selector = false
            info.text = resources.getString(temp)
            colorInfoList.add(info)
        }
        recyclerViewLabelColor.layoutManager = GridLayoutManager(this, 8)
        colorAdapter = ColorAdapter(this, colorInfoList)
        recyclerViewLabelColor.adapter = colorAdapter
        colorAdapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {
                colorAdapter.update(position)

            }

            override fun onLongClick(position: Int) {

            }

        }

    }

    val colorList = arrayListOf<Int>(
        R.string.color_1, R.string.color_2, R.string.color_3,
        R.string.color_4, R.string.color_5, R.string.color_6,
        R.string.color_7, R.string.color_8, R.string.color_9,
        R.string.color_10, R.string.color_11, R.string.color_12
    )


    lateinit var labAdapter: LableAdapter
    var labTextList: ArrayList<FileInfo>? = null

    lateinit var sheQuAdapter: LableAdapter
    var sheQuList: ArrayList<FileInfo>? = null

    /**
     * 话题信息添加
     */
    private fun initLabel(list: ArrayList<FileInfo>) {
        this.labTextList = list
        for (temp in list) {
            temp.selector = false
        }

        flexLabelRecyclerView.layoutManager =
            StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)
        labAdapter = LableAdapter(this, list)
        flexLabelRecyclerView.adapter = labAdapter
        labAdapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {
                labAdapter.update(position)
            }

            override fun onLongClick(position: Int) {

            }
        }

        imageViewAdd.setOnClickListener {
            addTabText()
        }

    }

    /**
     * 添加话题信息
     */
    private fun addTabText() {
        editLinearLayout.visibility = View.VISIBLE
        editQuery.isFocusable = true
        editQuery.isFocusableInTouchMode = true
        editQuery.requestFocus()
        editQuery.findFocus()

        showInput()
        btSend.setOnClickListener {

            val text = editQuery.text.toString()
            if (text != "") {
                send!!.addText(text, handler)
                editLinearLayout.visibility = View.GONE
                showInput()
                editQuery.isEnabled = false

            } else {
                showToastShort("请输入内容")
            }
        }

    }

    var picItem: PicItem? = null
    var chooseFile: File? = null

    /**
     * 多选图片的集合信息
     */
    var choosePicList = arrayListOf<String>()

    /**
     * 选择的视频信息
     */
    var chooseVideoUri: Uri? = null
    /**
     * 选择的表情信息
     */
    var chooseExpression: VideoInfo? = null
    /**
     * 选择的音频信息
     */
    var chooseVoice: String? = ""

    /**
     *  1 为拍照   2 为选择照片  3 为表情     4 为给音频配图片  5 多图上传
     */
    var chooseCode = 1

    /**
     * 选择图片返回，上传
     */
    fun savePic(picItem: PicItem) {

        this.picItem = picItem

        if (isVoiceAddPic) {
            chooseCode = 4
        } else {
            chooseCode = 2
        }

        val url = picItem.uri
        send!!.upImagePic(url, Share.getId(this).toString(), handler!!)

        showLoadDialog("上传中")

    }


    /**
     * 多图的张数
     */
    var chooseMoreIndexNum = 1

    /**
     * 多图上传
     */
    fun savePicList(list: ArrayList<String>) {

        this.choosePicList = list

        chooseCode = 5

        for (i in list.indices) {
            val temp = list[i]
            send!!.upImagePic(temp, Share.getId(this).toString(), i, handler!!)
        }

        showLoadDialog("上传中")
    }

    /**
     * 保存拍照的图片文件
     */
    fun saveFile(file: File) {
        if (isVoiceAddPic) {
            chooseCode = 4
        } else {
            chooseCode = 1
        }

        this.chooseFile = file

        send!!.upImagePic(file.absolutePath, Share.getId(this).toString(), handler!!)
        showLoadDialog("上传中")
    }


    /**
     * 保存视频
     */
    fun saveVideo(uri: Uri?) {

        StatusBarUtil.setStatusBarLightMode(window, true)

        this.chooseVideoUri = uri

        val code = send!!.upVideo(uri!!.path, Share.getId(this).toString(), handler!!)

        if (code == 1) {
            showLoadDialog("上传中")
        } else if (code == 2) {
            showToastShort("文件不存在，请重新选择")
        }

    }


    /**
     * 显示表情
     */
    fun saveExpression(newsInfo: VideoInfo) {
        this.chooseExpression = newsInfo

        chooseCode = 3

        picList.add(newsInfo.id.toString())

        showPic(newsInfo.domainname + newsInfo.path)

    }

    /**
     * 保存录音
     */
    fun saveVoice(fileName: String?) {

        this.chooseVoice = fileName

        val code = send!!.updateVoice(fileName!!, Share.getId(this).toString(), handler!!)
        if (code == 1) {
            showLoadDialog("上传中")
        } else {
            showToastShort("录音失败，请重新录制")
        }

        play(File(fileName))

    }


    fun play(file: File?) {

        log("voicePath---------${file!!.absolutePath}")


        if (file.exists()) {

            log("文件存在-------" + file.name)

            val mediaPlayer = MediaPlayer()
            mediaPlayer.setDataSource(file.absolutePath)
            mediaPlayer.prepareAsync()

            mediaPlayer.setOnPreparedListener {
                mediaPlayer.start()
            }

            mediaPlayer.setOnCompletionListener {
                it.release()
            }
        }

    }


    fun deleteListId(position: Int) {
        val info = showPicList[position]
        when (info.code) {
            1, 4 -> {
                picList?.remove(info.idStr)
            }
            2 -> {
                videoList?.remove(info.idStr)
            }
            3 -> {
                voiceList?.remove(info.idStr)
            }
        }

        showPicList.removeAt(position)
        picAdapter.notifyItemRemoved(position)

    }

}